import { cityApi } from "@/utils/api";

// 城市模块
const cityModule = {
  // 让其拥有命名空间
  // 默认情况下，getters/mutations/actions都是不需要加模块名的
  // 所有东西都要加模块名
  namespaced: true,
  state: {
    cityName: localStorage.getItem("name") || "北京",
    cityId: localStorage.getItem("id") || 110100,

    // 数据也要放到vuex
    // 城市相关数据
    cityList: [],
  },
  mutations: {
    // 城市相关的同步函数
    changeCity(state, payload) {
      state.cityName = payload.name;
      state.cityId = payload.id;
    },
    getCityList(state, payload) {
      state.cityList = payload.result;
    },
  },
  actions: {
    // 城市数据的异步函数
    async getCityListAsync({ commit }) {
      const res = await cityApi();
      commit("getCityList", res);
    },
  },
  getters: {
    // 城市相关的计算属性
    hotCity(state) {
      // 对象
      return state.cityList[0];
    },
    otherCity(state) {
      return state.cityList.slice(1);
    },
  },
};

export default cityModule;
